package top.jacktgq.sxt.bio.udp.demo8;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @Author CandyWall
 * @Date 2019/10/21--10:00
 * @Description 接收端：使用面向对象封装
 */
public class TalkReceive implements Runnable {
    private DatagramSocket server;
    private String name;

    public TalkReceive(int port, String name) {
        this.name = name;
        try {
            //1、使用DatagramSocket指定端口 创建接收端
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            //2、准备容器 封装成DatagramPacket包裹
            byte[] container = new byte[1024*60];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            //3、阻塞式接收包裹receive(DatagramPacket p)
            try {
                server.receive(packet);
                //4、分析数据 byte[] getData() getLenth()
                byte[] data = packet.getData();
                int len = packet.getLength();
                String content = new String(data, 0, len);
                System.out.println(name + ":" + content);
                if ("bye".equals(content)) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //5、释放资源
        server.close();
    }
}
